//
//  PictureCollectionView.swift
//  我的微博
//
//  Created by gongjunna on 15/8/2.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

class PictureCollectionView: UICollectionView {

    private  let flow :UICollectionViewFlowLayout = {
        let fl = UICollectionViewFlowLayout()
        return fl
        }()
    var status : Statu? {
        didSet {
        
            sizeToFit()
            // MARK: - 多线程 异步执行
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        let size : CGSize = getSize()
        print(size.width)
         print(size.height)
        return getSize()
    }
    
    func getSize() -> CGSize {
        let w = 90
        let margin = 10
        flow.itemSize = CGSize(width: 90, height: 90)
        let number = status?.pictureUrls?.count ?? 0
        print(number)
        if number == 0 {
        return  CGSizeZero
            
        }
        if number == 1
        {
            flow.itemSize = CGSize(width: 150, height: 150)
            
            return  flow.itemSize
        }
        if number == 4
        {
            let wid = 2 * w + margin
            
            return CGSize(width: wid, height: wid)
            
        }
        
        let  row = (number - 1) / 3 + 1
        
        let widt = w * 3 + margin  * 2
        
        let heigh = w * row + margin * (row-1)
        
        return CGSize(width: widt, height: heigh)
    
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flow)
        
        self.dataSource = self
        registerClass(PictureCell.self , forCellWithReuseIdentifier: "CELL")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension  PictureCollectionView : UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return status?.pic_urls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! PictureCell
       cell.url = status?.pictureUrls![indexPath.row]
        return cell
    }

}
class PictureCell : UICollectionViewCell {

    override init(frame: CGRect){
        super.init(frame: frame)
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    var url : NSURL? {
        didSet{
        
            iconV.setImageWithURL(url)
        }   
    
    }
    
 func  prepareUI() {
        contentView.addSubview(iconV)
    
        iconV.ff_Fill(contentView)
    }
    
    lazy var iconV : UIImageView = UIImageView()
    
}
